package com.cnpc.fyupdate.db.db;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;


import com.cnpc.fyupdate.db.test.SmartDownloadBean;

import java.util.HashMap;
import java.util.Map;

/**
 * 操作数据库的utils
 *
 * @author dllik 2013-11-23
 */
public class DBUtils {

    public static Uri URI_SMARTDOWNLOAD = IssContentProvider.buildUri(SmartDownloadBean.class);



    /**
     * 获取每条线程已经下载的文件长度
     *
     * @param context
     * @param downpath
     * @return
     */
    public static Map<Integer, Integer> querySmartDownData(Context context, String downpath) {
        ContentResolver mResolver = context.getContentResolver();
        Cursor cursor = mResolver.query(URI_SMARTDOWNLOAD, null, "downpath=?", new String[] {
                downpath
        }, null);
        Map<Integer, Integer> data = new HashMap<Integer, Integer>();
        while (cursor.moveToNext()) {
            SmartDownloadBean bean = new SmartDownloadBean();
            bean.cursorToBean(cursor);
            data.put(bean.threadid, bean.downlength);
        }
        cursor.close();
        return data;
    }

    /**
     * 保存每条线程已经下载的文件长度
     *
     * @param context
     * @param path
     * @param map
     */
    public static void insertSmartDown(Context context, String path, Map<Integer, Integer> map) {
        ContentResolver mResolver = context.getContentResolver();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            SmartDownloadBean bean = new SmartDownloadBean();
            bean.downpath = path;
            bean.downlength = entry.getValue();
            bean.threadid = entry.getKey();
            mResolver.insert(URI_SMARTDOWNLOAD, bean.beanToValues());
        }
    }

    /**
     * 实时更新每条线程已经下载的文件长度
     *
     * @param context
     * @param path
     * @param map
     */
    public static void updateSmartDown(Context context, String path, Map<Integer, Integer> map) {
        ContentResolver mResolver = context.getContentResolver();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            SmartDownloadBean bean = new SmartDownloadBean();
            bean.downpath = path;
            bean.downlength = entry.getValue();
            bean.threadid = entry.getKey();
            mResolver.update(URI_SMARTDOWNLOAD, bean.beanToValues(), "downpath=? and threadid=?",
                    new String[] {
                            bean.downpath, bean.threadid + ""
                    });
        }
    }

    /**
     * 当文件下载完成后，删除对应的下载记录
     *
     * @param context
     * @param path
     */
    public static void deleteSmartDown(Context context, String path) {
        ContentResolver mResolver = context.getContentResolver();
        mResolver.delete(URI_SMARTDOWNLOAD, "downpath=?", new String[] {
                path
        });
    }



}
